//
//  WYLoginController.m
//  Boss
//
//  Created by admin on 2018/5/31.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "WYLoginController.h"
#import "YYText.h"
#import "UIView+Extension.h"
#import "UIButton+CountDown.h"
#import "ZYMainController.h"
#import "WYBindlingWeChatController.h"
#import "WYAgreementController.h"
@interface WYLoginController ()<UITextFieldDelegate>
{
    NSUInteger i;
}

@property (strong, nonatomic) IBOutlet UITextField *numberTextField;

@property (strong, nonatomic) IBOutlet UITextField *codeTextField;
@property (strong, nonatomic) IBOutlet UIButton *codeBtn;
@property (strong, nonatomic) IBOutlet UIButton *loginBtn;
@property (nonatomic,strong) UIActivityIndicatorView *indicatorView;
@property (nonatomic,strong) YYLabel *label;
@end

@implementation WYLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    i=0;
    [self setupUI];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   // [self wr_setNavBarBackgroundAlpha:0];
    self.navigationController.navigationBar.hidden = YES;
}


-(void)setupUI
{
    WEAKSELF
    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhite)];
    self.indicatorView = indicatorView;
    [self.loginBtn addSubview:indicatorView];
    [indicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(weakSelf.loginBtn);
        make.width.height.mas_equalTo(40);
    }];
    
    
    
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.codeBtn.userInteractionEnabled = NO;
    self.loginBtn.userInteractionEnabled  = NO;
    
    [self.codeBtn setTitleColor:[UIColor hexStringToColor:@"#e38b78" alpha:1.0] forState:UIControlStateNormal];
    
    
    [self.loginBtn setBackgroundColor:[UIColor hexStringToColor:@"#e38b78" alpha:1.0]];
    
    [self.numberTextField addTarget:self action:@selector(numberTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    [self.codeTextField addTarget:self action:@selector(numberTextFieldChanged:) forControlEvents:UIControlEventEditingChanged];
    
    
    
    YYLabel *label = [YYLabel new];
    self.label = label;
    [self.view addSubview:label];
    label.numberOfLines = 0;
    label.preferredMaxLayoutWidth =(kScreenWidth - 2 * 16);
    label.left = 16;
    label.width = (kScreenWidth - 2 * 16);
    label.textVerticalAlignment = YYTextVerticalAlignmentTop;
    label.displaysAsynchronously = YES;
    label.ignoreCommonProperties = YES;
    label.fadeOnHighlight = NO;
    label.textColor = kColor999999;
    
    label.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
        WYAgreementController *amc = [[WYAgreementController alloc]init];
        [weakSelf.navigationController pushViewController:amc animated:YES];
        
        
    };
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(42);
        make.top.mas_equalTo(self.loginBtn.y+self.loginBtn.height+20);
        make.right.mas_equalTo(-42);
    }];
    [self setLabelText];
    
    self.numberTextField.clearButtonMode=UITextFieldViewModeWhileEditing;
}

-(void)setLabelText
{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:@"未注册过巨牛boos的手机号，登录时将自动注册且代表您已经同意《巨牛BOSS用户注册协议》"];

    NSString *string = @"《巨牛BOSS用户注册协议》";
    NSRange searchRange = NSMakeRange(0, attributedString.string.length);
    NSRange range = [attributedString.string rangeOfString:string options:kNilOptions range:searchRange];
    [attributedString yy_setColor:kColor999999 range:NSMakeRange(0, range.location)];
    if (range.location == NSNotFound) return;
    if ([attributedString yy_attribute:YYTextHighlightAttributeName atIndex:range.location] == nil) {
        [attributedString yy_setColor:[UIColor hexStringToColor:@"#466DB0" alpha:1.0] range:range];
        
        // 高亮状态
        YYTextHighlight *highlight = [YYTextHighlight new];
        [attributedString yy_setTextHighlight:highlight range:range];
    }

    self.label.attributedText = attributedString;
    self.label.textAlignment = NSTextAlignmentCenter;
}






-(void)numberTextFieldChanged:(UITextField *)textField
{
    if (textField == self.numberTextField) {
        
        if (textField.text.length > i) {
            if (textField.text.length == 4 || textField.text.length == 9 ) {//输入
                NSMutableString * str = [[NSMutableString alloc ] initWithString:textField.text];
                [str insertString:@" " atIndex:(textField.text.length-1)];
                textField.text = str;
            }
            if (textField.text.length >= 13 ) {//输入完成
                textField.text = [textField.text substringToIndex:13];
                [self.codeBtn setTitleColor:kColorMainColor forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = YES;
            }else{
                [self.codeBtn setTitleColor:[UIColor hexStringToColor:@"#e38b78" alpha:1.0] forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = NO;
                
                
            }
            i = textField.text.length;
            
        }else if (textField.text.length < i){//删除
            if (textField.text.length == 4 || textField.text.length == 9) {
                textField.text = [NSString stringWithFormat:@"%@",textField.text];
                textField.text = [textField.text substringToIndex:(textField.text.length-1)];
            }
            i = textField.text.length;
        }
        
        
    }
    if (textField == self.codeTextField) {
        if (textField.text.length > 6){
            textField.text = [textField.text substringToIndex:6];
        }
    }
    if (self.codeTextField.text.length==6&&self.numberTextField.text.length==13) {
        [self.loginBtn setBackgroundColor:kColorMainColor];
        self.loginBtn.userInteractionEnabled = YES;
    }else{
        [self.loginBtn setBackgroundColor:[UIColor hexStringToColor:@"#e38b78" alpha:1.0]];
        self.loginBtn.userInteractionEnabled = NO;
    }
}
- (IBAction)exitAction:(id)sender {
     NSLog(@"退出");
    [self.numberTextField resignFirstResponder];
    [self.codeTextField resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (IBAction)codeAction:(id)sender {
     NSLog(@"获取验证码");
    
    
    if (![NSString isPhone:[self.numberTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""]]) {
        [self toast:@"请输入正确的手机号"];
        return;
    }
    [self.codeBtn startWithTime:59 title:@"重新获取" countDownTitle:@"s后重新获取" mainColor:[UIColor whiteColor] countColor:kColorMainColor];
  //  WEAKSELF
    [WYHttpServer sendMessageWithPhone:[self.numberTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""] SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
//        if (success) {
//
//        }else{
//            [weakSelf toast:errorMessage];
//        }
    }];
   //  UIButton *btn =(UIButton *)sender;
    
}
- (IBAction)loginAction:(id)sender {
    
     UIButton *btn = (UIButton *)sender;
    [self.indicatorView startAnimating];
    [btn setTitle:@"" forState:UIControlStateNormal];
    NSLog(@"登录");
    WEAKSELF
    [WYHttpServer masterLoginWithUserName:[self.numberTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""] WithCode:self.codeTextField.text SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            [WYStoreModule storeToken:response[@"result"][@"token"]];
            [WYStoreModule storeUserId:response[@"result"][@"userId"]];
            [weakSelf sendRegistrationID:@""];
            //[weakSelf sendShare];
        }else{
            if ([response[@"code"]integerValue] == 1007) {
                [WYStoreModule storeTempToken:response[@"result"][@"token"]];
                
                [WYStoreModule storeTempUserId:response[@"result"][@"userId"]];
                
                
                
                //[weakSelf sendShare];
                WYBindlingWeChatController *bwc = [[WYBindlingWeChatController alloc]init];
                bwc.phone  = [self.numberTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
                [self.navigationController pushViewController:bwc animated:YES];
            }else{
                 [weakSelf toast:errorMessage];
            }
            
            
//            if([response[@"code"] integerValue]==1007]){
//                
//                WYBindlingWeChatController *bwc = [[WYBindlingWeChatController alloc]init];
//                [self.navigationController pushViewController:bwc animated:YES];
//                
//                
//            }
            
            
            

//
         //

        }
        [self.indicatorView stopAnimating];
        [btn setTitle:@"登录" forState:UIControlStateNormal];
    }];
//
//
//
//
//
//    if (self.indicatorView.isAnimating) {
//
//    }else{
//
//   }
}
-(void)sendRegistrationID:(NSString *)registrationID
{
    registrationID = [WYStoreModule currentRegisterId];
    [WYHttpServer upLoadDateId:registrationID SucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            
        }
        
        
    }];
    
    
}


-(void)sendShare
{
    [WYHttpServer getShareRedPacketSucessBlock:^(BOOL success, id response, NSString *errorMessage) {
        if (success) {
            
        }
        
        
    }];
    
    
}
@end
